<?php
namespace app\admin\model;

use app\common\model\CommonBase;
use app\common\service\Dynamic;
use app\common\service\RedisComm;
use app\admin\model\BondRate;
use app\admin\model\Chip;

class Baseinfo extends Base{

    protected $name = 'stock_base_info';
    const STOCK_BASE_INFO = 'https://emweb.securities.eastmoney.com/PC_HSF10/OperationsRequired/OperationsRequiredAjax?times=1&code=';
    const PERCENTAGE = 'https://emweb.securities.eastmoney.com/PC_HSF10/NewFinanceAnalysis/DBFXAjaxNew?code=';
    const IS_ZFMX = 'http://emweb.securities.eastmoney.com/PC_HSF10/BonusFinancing/PageAjax?code=';
    const PLEDGE_RATIO = 'https://basic.10jqka.com.cn/basicapi/finance/stock/maintable/index_merge/?code=';
    const CURRENT_RATIO = 'https://emweb.securities.eastmoney.com/PC_HSF10/NewFinanceAnalysis/ZYZBAjaxNew?type=0&code=';
    const COMPANY = 'http://emweb.securities.eastmoney.com/PC_HSF10/CompanySurvey/CompanySurveyAjax?code=';
    const MGJYXJL = 'https://emweb.securities.eastmoney.com/PC_HSF10/NewFinanceAnalysis/ZYZBAjaxNew?type=0&code='; //每股经营现金流
    const MGJBSY = 'https://emweb.securities.eastmoney.com/PC_HSF10/OperationsRequired/PageAjax?code='; //每股基本收益
    //最新指标
    const MAININDIC_START = "https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_MAINFINADATA&sty=APP_F10_MAINFINADATA&filter=(";
    const MAININDIC_END = ")&p=1&ps=9&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=";

    protected $bondrate = null;
    protected $chip = null;

    public function initialize(){

        $this->bondrate = new BondRate();
        $this->chip = new Chip();
    }

    public function baseInfoDataHandle($v=[]){

        $interestRate = $this->bondrate->bondRate();
        $time = date('Y',time());
        $time++;
        $intrinsic_value = 0;
        $baseTmp = [] ;
        $valuationTmp = [] ;
        $baseTmp = $this->base->where(['sid'=>$v['sid'], 'stock_code'=>$v['stock_code']])->find();
        $valuationTmp = $this->valuationDb->where(['sid'=>$v['sid'], 'stock_code'=>$v['stock_code'], 'year'=>$time])->find();
        $stock_cache_key_gl_intrinsic = $v['jys'].$v['stock_code'].'_gl_intrinsic';
        $stock_cache_key_gl_intrinsic_a = $v['jys'].$v['stock_code'].'_gl_intrinsic_a';
        $intrinsic_value = false;
        $intrinsic_value = CommonBase::cGet($stock_cache_key_gl_intrinsic);
        $a = CommonBase::cGet($stock_cache_key_gl_intrinsic_a);
        $baseTmp['price'] = $v['price'];

        if($intrinsic_value == false){
            
            if(!empty($baseTmp['one_base_earnings']) && is_numeric($baseTmp['one_base_earnings'])){
                
                $ratio = 0.00;
                if(!empty($valuationTmp['ratio']) && is_numeric($valuationTmp['ratio'])){
                    $ratio = floatval($valuationTmp['ratio']);
                    if($ratio<=0){
                        $ratio = 0.00;
                    }
                }
                
                $liability_interest_rate = !empty($baseTmp['liability_interest_rate']) ? floatval($baseTmp['liability_interest_rate']) : $interestRate['interest_rate'] ;
                $intrinsic_value = $baseTmp['one_base_earnings']*(2*$ratio+8.5)*4.4/$liability_interest_rate;
                $intrinsic_value = sprintf("%.2f",$intrinsic_value);
                
                $a = '';
                $a = $baseTmp['one_base_earnings']."(2*{$valuationTmp['ratio']}+8.5)*4.4/{$liability_interest_rate}\n";
                
                $baseTmp['ratio'] = $valuationTmp['ratio'];

                CommonBase::cSet($stock_cache_key_gl_intrinsic, $intrinsic_value);
                CommonBase::cSet($stock_cache_key_gl_intrinsic_a, $a);
            }else{
                $intrinsic_value = '';
            }
        }
        $baseTmp['gl_intrinsic'] = $intrinsic_value;
        $baseTmp['gl_a'] = $a;
        
        if(!empty($baseTmp['gross_profit_rate'])){
            $baseTmp['gross_profit_rate'] = sprintf("%.2f",$baseTmp['gross_profit_rate']);
        }else{
            $baseTmp['gross_profit_rate'] = '';
        }
        if(!empty($baseTmp['net_assets_profit'])){
            $baseTmp['net_assets_profit'] = sprintf("%.2f",$baseTmp['net_assets_profit']);
        }else{
            $baseTmp['net_assets_profit'] = '';
        }

        $lqPegKey = $v['jys'].$v['stock_code'].'_lq_peg';
        $baseTmp['lq_peg'] = false;
        $baseTmp['lq_peg'] = CommonBase::cGet($lqPegKey);
        if($baseTmp['lq_peg'] == false){

            if(is_numeric($v['price_earnings_ratio_ttm']) && $ratio>0){
                $baseTmp['lq_peg'] = sprintf("%.2f",floatval($v['price_earnings_ratio_ttm'])/$ratio);
            }else{
                $baseTmp['lq_peg'] = $v['price_earnings_ratio_ttm'];
            }
            CommonBase::cGet($lqPegKey, $baseTmp['lq_peg']);
        }
        $v['jys'] = mb_strtolower($v['jys']);
        
        $stock_cache_key_pcf = $v['jys'].$v['stock_code'].'_pcf';
        $pcfTmp = false;
        $pcfTmp = CommonBase::cGet($stock_cache_key_pcf);
        if($pcfTmp == false){
            $baseTmp['one_usiness_cash_flow'] = !empty($baseTmp['one_business_cash_flow']) ? floatval($baseTmp['one_business_cash_flow']) : 0 ;
            if($baseTmp['one_business_cash_flow']!=0){
                $baseTmp['pcf'] = sprintf("%.2f",$baseTmp['price']/$baseTmp['one_business_cash_flow']);
                CommonBase::cSet($stock_cache_key_pcf,$baseTmp['pcf']);
            }else{
                $baseTmp['pcf'] = ''; 
            }
        }else{
            $baseTmp['pcf'] = $pcfTmp;  
        }
        
        $baseTmp['gross_liability'] = !empty($baseTmp['gross_liability']) ? floatval($baseTmp['gross_liability']) : 0;
        $baseTmp['monetary_assets'] = !empty($baseTmp['monetary_assets']) ? floatval($baseTmp['monetary_assets']) : 0;
        if($baseTmp['monetary_assets']!=0){
            $baseTmp['monetary_assets'] = sprintf("%.2f",$baseTmp['gross_liability']/$baseTmp['monetary_assets']);
        }else{
            $baseTmp['monetary_assets'] = ''; 
        }
        $baseTmp['zxzb1'] = '';
        $baseTmp['zxzb2'] = '';
        $baseTmp['cl'] = '';
        if(!empty($baseTmp['gl_intrinsic']) && is_numeric($baseTmp['gl_intrinsic'])){
            $baseTmp['gl_intrinsic'] = floatval($baseTmp['gl_intrinsic']);
            $baseTmp['cl'] = floatval($baseTmp['price'])/$baseTmp['gl_intrinsic'];
            $baseTmp['cl'] = sprintf("%.2f", $baseTmp['cl']);
        }
        $baseTmp['dividend_yield_ratio'] = '';
        $stock_cache_key_dividend_yield_ratio = $v['jys'].$v['stock_code'].'_dividend_yield_ratio';
        $baseTmp['dividend_yield_ratio'] = CommonBase::cGet($stock_cache_key_dividend_yield_ratio);
        if($baseTmp['dividend_yield_ratio'] == false){
            if(!empty($baseTmp['dividend'])){
                $dividend_implode = explode(',',$baseTmp['dividend']);
                $baseTmp['dividend_yield_ratio'] = sprintf("%.4f",$dividend_implode[0] / $baseTmp['price']);
                $baseTmp['dividend_yield_ratio'] = $baseTmp['dividend_yield_ratio']*100;
                $baseTmp['dividend_implode'] = $baseTmp['dividend_yield_ratio'];
                $baseTmp['dividend_yield_ratio'].=$dividend_implode[1];
                
                CommonBase::cSet($stock_cache_key_dividend_yield_ratio, $baseTmp['dividend_yield_ratio']);
            }else{
                $baseTmp['dividend_implode'] = 0;
            }
        }
        return $baseTmp;
    }

    //证券基本信息-操盘必读
    public function getStockBaseInfo($val=[], $sid=0){

        $reMainIndic = file_get_contents(self::MAININDIC_START.urlencode('SECUCODE="'.$val['stock_code'].'.'.$val['jys'].'"').self::MAININDIC_END);
        $arr = [];
        if(!empty($reMainIndic)){
            $reMainIndic = json_decode($reMainIndic,true);
            $reMainIndic = $reMainIndic['result']['data'][0];

            //基本每股收益
            $arr['one_base_earnings'] = 0;
            if(!empty($reMainIndic['EPSJB'])){
                $arr['one_base_earnings'] = substr(sprintf("%.3f",$reMainIndic['EPSJB']) , 0,-1);
            }
            //每股经营现金流
            $arr['one_business_cash_flow'] = 0;
            if(!empty($reMainIndic['MGJYXJJE'])){
                $arr['one_business_cash_flow'] = substr(sprintf("%.3f",$reMainIndic['MGJYXJJE']) , 0,-1);
            }
            //每股公积金
            $arr['one_provident_fund'] = 0;
            if(!empty($reMainIndic['MGZBGJ'])){
                $arr['one_provident_fund'] = substr(sprintf("%.3f",$reMainIndic['MGZBGJ']) , 0,-1);
            }
            //每股未分配利润
            $arr['one_undistributed_profits'] = 0;
            if(!empty($reMainIndic['MGWFPLR'])){
                $arr['one_undistributed_profits'] = substr(sprintf("%.3f",$reMainIndic['MGWFPLR']) , 0,-1);
            }
            //净资产收益率
            $arr['net_assets_profit'] = 0;
            if(!empty($reMainIndic['ROEJQ'])){
                $arr['net_assets_profit'] = substr(sprintf("%.3f",$reMainIndic['ROEJQ']) , 0,-1);
            }
            //资产负债率
            $arr['asset_liability_ratio'] = 0;
            if(!empty($reMainIndic['ZCFZL'])){
                $arr['asset_liability_ratio'] = substr(sprintf("%.3f",$reMainIndic['ZCFZL']) , 0,-1);
            }
            //毛利率
            $arr['gross_profit_rate'] = 0;
            if(!empty($reMainIndic['XSMLL'])){
                $arr['gross_profit_rate'] = substr(sprintf("%.3f",$reMainIndic['XSMLL']) , 0,-1);
            }                     
            //总资产周转天数(天)
            $arr["zzczzts"] = 0;
            if(!empty($reMainIndic['ZZCZZTS'])){
                $arr['zzczzts'] = substr(sprintf("%.3f",$reMainIndic['ZZCZZTS']) , 0,-1);
            }
        }
        $reVal = '';
        $reVal = $this->getUrl(self::STOCK_BASE_INFO.$val['jys'].$val['stock_code']);
        $reVal = json_decode($reVal,true);
        $reVal['zxzb1'] = trim($reVal['zxzb1']);

        $reTmpZxzb1 =  $reTmp = strip_tags($reVal['zxzb1']);

        $arr['zxzb1'] = $reVal['zxzb1'];
        $arr['zxzb2'] = $reVal['zxzb2'];

        //更新公司信息表
        preg_match('/总股本\(万股\)(.*?)稀/', $reTmpZxzb1,$capital_stock);
        preg_match('/流通股本\(万股\)(.*?)数/', $reTmpZxzb1,$tradable_shares);
        $securitie = new Securities();
        $capital_stock = !empty($capital_stock[1]) ? trim($capital_stock[1]) : '';
        $tradable_shares = !empty($tradable_shares[1]) ? trim($tradable_shares[1]) : '';
        $securitie->securitieInfoUpdate($sid, $val['stock_code'], ['capital_stock'=>$capital_stock, 'tradable_shares'=>$tradable_shares]);

        $percentage = $this->getUrl(self::PERCENTAGE.$val['jys'].$val['stock_code']);
        $percentage = json_decode($percentage, true);
        //总资产
        $arr['total_assets'] = !empty($percentage['bgq'][0]['TOTAL_ASSETS']) ? trim($percentage['bgq'][0]['TOTAL_ASSETS']) : '';
        //货币资金
        $arr['monetary_assets'] = !empty($percentage['bgq'][0]['MONETARYFUNDS']) ? trim($percentage['bgq'][0]['MONETARYFUNDS']) : '';
        $arr['account_receivable'] = !empty($percentage['bgq'][0]['ACCOUNTS_RECE']) ? trim($percentage['bgq'][0]['ACCOUNTS_RECE']) : '';
        $arr['inventory'] = !empty($percentage['bgq'][0]['INVENTORY']) ? trim($percentage['bgq'][0]['INVENTORY']) : '';
        $arr['gross_liability'] = !empty($percentage['bgq'][0]['TOTAL_LIABILITIES']) ? trim($percentage['bgq'][0]['TOTAL_LIABILITIES']) : '';
        //增发明细
        $is_zfmx = $this->getUrl(self::IS_ZFMX.$val['jys'].$val['stock_code']);
        $is_zfmx = json_decode($is_zfmx,true);
        $arr['is_zfmx'] = 0;
        if(!empty($is_zfmx['zfmx']) && count($is_zfmx['zfmx'])>0){
            $arr['is_zfmx'] = 1;
        }
        $arr['dividend'] = $this->dividend($is_zfmx['fhyx']);

        $pledgeProportion = $this->getUrl(self::PLEDGE_RATIO.$val['stock_code']);
        $pledgeProportion = json_decode($pledgeProportion, true);

        $arr['gross_operating_income'] = '';
        $arr['net_profit_ratio'] = '';
        $arr['net_goodwill'] = '';
        $arr['equity_pledge'] = '';
        foreach ($pledgeProportion['data']['main_table']['index_list'] as $kZy => $vZy) {

            if($vZy['index_name'] == '营业总收入'){
                $arr['gross_operating_income'] = !empty($vZy['value']) ? trim($arr['value']) : '' ;
            }
            if($vZy['index_name'] == '净利率'){
                $arr['net_profit_ratio'] = !empty($vZy['value']) ? trim($arr['value']) : '' ;
            }
            if($vZy['index_name'] == '商誉净资产比'){
                $arr['net_goodwill'] = !empty($vZy['value']) ? trim($arr['value']) : '' ;
            }
            if($vZy['index_name'] == '质押总股本比'){
                $arr['equity_pledge'] = !empty($vZy['value']) ? sprintf("%.2f",$vZy['value']).'%' : '' ;
            }
        }

        $arr['view_results_title'] = !empty($pledgeProportion['data']['release_status']['report_name']) ? trim($pledgeProportion['data']['release_status']['report_name']) : '' ;
        $arr['view_results'] = !empty($pledgeProportion['data']['release_status']['url']) ? str_replace('//','http://',$pledgeProportion['data']['release_status']['url']) : '' ;

        $currentRatio = $this->getUrl(self::CURRENT_RATIO.$val['jys'].$val['stock_code']);
        $currentRatio = json_decode($currentRatio, true);
        $arr['current_ratio'] = !empty($currentRatio['data'][0]['LD']) ? sprintf("%.2f", $currentRatio['data'][0]['LD']) : '' ;
        $arr['zzczzts'] = intval($currentRatio['data'][0]['ZZCZZTS']);

        $reSecurities = self::where(['sid'=>$sid, 'stock_code'=>$val['stock_code']])->find();
        if(!empty($reSecurities['sid'])){
            return self::where(['sid'=>$reSecurities['sid']])->update($arr);
        }else{
            $arr['sid'] = $sid;
            $arr['stock_code'] = $val['stock_code'];
            return $this->insertGetId($arr);
        }
    }

    //分红派息
    protected function dividend($arr=[]){

        $time = time();
        $year = date('Y',$time);
        $month = date('m',$time);

        $dividend_yield_ratio = '';
        foreach($arr AS $v){

            preg_match('/派(.*)元/', $v['IMPL_PLAN_PROFILE'], $gxProice);
            if(!empty($gxProice[1])){

                $NOTICE_DATE = strtotime($v['NOTICE_DATE']);
                $NOTICE_DATE_YEAR = date('Ym', $NOTICE_DATE);
                $dividend_yield_ratio = sprintf("%.4f", floatval($gxProice[1])/10);
                $dividend_yield_ratio.= ',%('.$NOTICE_DATE_YEAR.')';
                break;
            }
        }
        return $dividend_yield_ratio;
    }

    //删除证券基本信息-操盘必读
    public function delStockBaseInfo($sid=0, $stock_code=''){
        $this->where(['sid'=>$sid,'stock_code'=>$stock_code])->delete();
    }

    //详情-操盘必读
    public function detailStockBaseInfo($sid=0, $stock_code=''){
        return $this->where(['sid'=>$sid,'stock_code'=>$stock_code])->find()->toArray();
    }

    //编辑
    public function editStockBaseInfo($data=[]){

        $data['sid'] = trim($data['sid']);
        $data['stock_code'] = trim($data['stock_code']);
        $this->chip->updateChip(['sid'=>$data['sid'], 'stock_code'=>$data['stock_code']], $data);

        $arr = [];
        if(!empty($data['price_sales_ratio'])){

            $arr['price_sales_ratio'] = trim($data['price_sales_ratio']);
        }else{
            $arr['price_sales_ratio'] = '';
        }

        if(!empty($data['liability_interest_rate'])){

            $arr['liability_interest_rate'] = trim($data['liability_interest_rate']);
        }else{
            $arr['liability_interest_rate'] = '';
        }

        if(!empty($data['equity_pledge'])){

            $arr['equity_pledge'] = trim($data['equity_pledge']);
        }else{
            $arr['equity_pledge'] = '';
        }

        if(!empty($data['is_zfmx'])){

            $arr['is_zfmx'] = trim($data['is_zfmx']);
        }else{
            $arr['is_zfmx'] = '';
        }

        $this->where(['sid'=>$data['sid'], 'stock_code'=>$data['stock_code']])->update($arr);
    }

    //股息率
    public static function DividendYield(int $sid = 0, string $stockCode = '', string $jys = ''){

        if($sid == 0 || $stockCode == '' || $jys == ''){
            return 0;
        }

        $k = 'stock:'.$jys.$stockCode.':dividend_yield_ratio';
        $result = RedisComm::Get($k);
        if(!empty($result)){
            return $result;
        }else{
            
            $dividend = [];
            $dividend = self::where(['sid'=> $sid])->find();
            if(empty($dividend['dividend'])){
                return 0;
            }
            $price = Dynamic::Price($stockCode, $jys) ?? [];
            $price['price'] = (float)$price['price'] ?? 0;
            if(empty($price['price']) || $price['price'] < 0.01){
                return 0;
            }
            $dividend = explode(',',$dividend['dividend']);
            if(empty($dividend) && count($dividend) < 1){
                return 0;
            }
            $dividend = $dividend[0];
            if(empty($dividend) && (float)$dividend < 0.01){
                return 0;
            }
            $dividendYieldRatio = (float)sprintf("%.4f",$dividend / $price['price']) ?? 0;
            if($dividendYieldRatio > 0){
                $dividendYieldRatio = ($dividendYieldRatio*100);
                $dividendYieldRatio = sprintf("%.2f",$dividendYieldRatio);
            }
            RedisComm::Set($k, $dividendYieldRatio, 86400);
            return $dividendYieldRatio;
        }
        return 0;
    }

    //操盘必读
    public static function BaseInfo(int $sid = 0, string $stockCode = '', string $jys = ''){

        if($sid == 0 || $stockCode == '' || $jys == ''){
            return false;
        }
        $ld = file_get_contents('https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_MAINFINADATA&sty=APP_F10_MAINFINADATA&quoteColumns=&filter=('.urlencode('SECUCODE="'.$stockCode.'.'.$jys.'"').')&p=1&ps=200&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=');
        if(!empty($ld)){
            $ld = json_decode($ld, true) ?? [];
            if(!empty($ld['result']['data']) && count($ld['result']['data']) > 0){
                $ld = $ld['result']['data'];
                $ld = sprintf("%.2f", $ld[0]['LD']);
            }
            if(self::where(['sid'=> $sid])->find() === null){
                self::where(['sid'=> $sid])->insert(['sid'=>$sid, 'current_ratio'=> $ld]);
            }else{
                self::where(['sid'=> $sid])->update(['current_ratio'=> $ld]);
            }
        }
    }
}